<template>
  <div>
    <div class="el-upload-dragger" id='browseButton'><i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </div>
    <div v-if='fileRawList.length' class="upload-item">
      <div class="upload-status">
        <span><i class="el-icon-document" style="margin-right: 5px;"></i>{{ fileRawList[0].name }}</span>
        <div class="warning-text">
          <span class="item" v-if="fileRawList[0].status === -1">正在计算MD5</span>
          <span class="item" v-if="fileRawList[0].status === 1 && fileRawList[0].percent === 0">MD5计算完成，准备上传</span>
          <span class="item" v-if="fileRawList[0].status === 4" style="color: brown">
            上传失败
            <!-- <i class="el-icon-circle-close"></i> -->
          </span>
          <span class="item" v-if="fileRawList[0].status === 5" style="color: chartreuse"><i
              class="el-icon-circle-check"></i></span>
          <span class="item"
            v-if='fileRawList[0].status === 2 || fileRawList[0].status === 1 && fileRawList[0].percent > 0'>{{fileRawList[0].percent}}%</span>
          <i class="el-icon-close close-icon" @click="deleteFile(fileRawList[0])"></i>
        </div>
      </div>
      <div class="progress">
        <el-progress v-if="fileRawList[0].percent || fileRawList[0].percent === 0" :stroke-width="2"
          :percentage="fileRawList[0].percent"
          :v-if="fileRawList[0].status === 2 || fileRawList[0].status === 1 && fileRawList[0].percent > 0" />
      </div>
      <div @click='uploadStart'>上传</div>
    </div>
  </div>
</template>
<script>
  // plupload参数文档：http://www.phpin.net/tools/plupload/
  import FileMd5 from '@/factory/file-md5.js'
  // import { removeFile } from '@/api/filemgr'
  export default {
    name: 'Plupload',
    head() {
      return {
        title: '分片上传'
      }
    },
    props: {
      // 文件上传类型限制
      acceptFiles: {
        type: String,
        default: '.png,.jpg,.bmp,.doc,.docx,.xls,.xlsx,.pdf,.rar,.zip'
      },
      bizType: {
        type: String,
        default: ''
      },
      fileList: {
        type: Array,
        default: () => []
      },
      limit: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        up: {},
        basicForm: {},
        fileRawList: [],
        uploading: false
      }
    },
    watch: {
      up(val) {
        this.fileRawList = this.fileList.concat(val.files)
      },
      acceptFiles(val) {
        this.up.refresh()
      }
      // fileList(val) {
      //   console.log('fileList', val, this.up)
      //   this.fileRawList = val.concat(this.up.files)
      //   this.up.refresh()
      // }
    },
    mounted() {
      this.pluploadInit()
    },
    methods: {
      pluploadInit() {
        var that = this
        var uploader = new this.$plupload.Uploader({
          browse_button: 'browseButton',
          drop_element: 'browseButton',
          url: 'https://httpbin.org/post',
          // url: 'http://192.168.8.132:80/jaz/upload',
          chunk_size: '10MB',
          // headers: that.headers,
          multipart: true, // 为true时将以multipart/form-data
          auto_start: true,
          max_retries: 0, // 当发生plupload.HTTP_ERROR错误时的重试次数，为0时表示不重试
          multi_selection: false, // 是否可以在文件浏览对话框中选择多个文件
          filters: {
            mime_types: [
              { extensions: that.acceptFiles.replace(/\./g, '') }
            ],
            prevent_duplicates: false, // 不允许选取重复文件
            max_file_size: '1024mb' // 最大只能上传400kb的文件
          },
          init: {
            BeforeUpload(up, file) {
              // 上传时的附加参数，以键/值对的形式传入
              up.setOption('multipart_params', {
                'size': file.size,
                'md5': file.md5,
                'bizType': that.bizType
              })
            },
            FileFiltered(up, files) {
              // up.start()
            },
            FilesAdded(up, files) {
              that.fileRawList.push(...files)
              if (that.fileRawList.length > that.limit) {
                that.deleteFile(that.fileRawList[0])
              }
              files.forEach((f) => {
                f.status = -1
                FileMd5(f.getNative(), (e, md5) => {
                  f['md5'] = md5
                  f.status = 1
                })
              })
            },
            FilesRemoved(upp, files) {
              that.uploading = false
            },
            FileUploaded(up, file, info) {
              if (info.status === 200) {
                console.log('FileUploaded', info, file, up)
                const { path } = JSON.parse(info.response).data
                file.url = path
                that.up.refresh()
                that.$emit('onChange', that.fileRawList)
              }
            },
            UploadComplete(up, files) {
              that.uploading = false
            },
            Error(up, args) {
              that.uploading = false
            }
          }
        })
        uploader.init()
        this.up = uploader
        // uploader.bind('FilesAdded', this.uploadStart)
      },
      deleteFile(row) {
        this.fileRawList.splice(this.fileRawList.indexOf(row), 1)
        var file = this.up.getFile(row.id)
        file && this.up.removeFile(file)
        // row.url && removeFile({ filePath: row.url }).then(res => {
        //   if (res.success) {
        //     this.$emit('onChange', this.fileRawList.filter(item => {
        //       return item.url
        //     }))
        //     return
        //   }
        //   this.$message.warning('删除文件出现异常，请与管理员联系!')
        // })
      },
      uploadStart() {
        this.uploading = true
        this.up.start()
      }
    }
  }
</script>
<style scoped>
  .upload-item {
    width: 370px;
    height: 25px;
    line-height: 25px;
  }

  .upload-status {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #606266;
    margin-top: 10px;
    padding: 0px 6px;
    border-radius: 4px;
  }

  .progress {
    position: relative;
  }

  .el-progress__text {
    display: none !important;
  }

  .warning-text {}

  .close-icon {
    display: none;
    line-height: 25px;
  }

  .upload-status:hover {
    background-color: #F5F7FA;
  }

  .upload-status:hover .close-icon {
    display: block;
  }

  .upload-status:hover .item {
    display: none;
  }

  .el-progress-bar {
    padding-right: 0 !important;
    margin-right: 0 !important;
  }
</style>